import 'dart:convert';
import 'dart:math';
import 'dart:typed_data';
import 'package:casdon/app/config/env/env_config.dart';
import 'package:casdon/app/config/env/env_provider.dart';
import 'package:encrypt/encrypt.dart' as encrypt;
import 'package:encrypt/encrypt.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:pointycastle/api.dart';
import 'package:pointycastle/asymmetric/api.dart';
import 'package:pointycastle/asymmetric/pkcs1.dart';
import 'package:pointycastle/asymmetric/rsa.dart';


/// 安全加密处理器
/// 提供 AES 和 RSA 混合加密方案
/// 使用方式：
/// 1. 生成 AES 密钥：generateAesKey()
/// 2. 加密数据：encryptData(text)
/// 3. 加密 AES 密钥：encryptAesKeyWithRsa()
class SecureEncryptor {
  final EnvConfig _envConfig;
  final String _rsaPublicKeyPem;
  // 1， 无论final与否，非空字段必须在构造函数执行之前赋值。
  // 2， final字段，无论非空与否，都必须在构造函数之前赋值。
  // 3， 能在构造函数体内赋值的字段，只能是非空且非final字段
    SecureEncryptor(this._envConfig) 
      : _rsaPublicKeyPem = _envConfig.request_publickey;
  // 状态
  Uint8List? _aesKeyBytes;

  /// 生成随机的 32 字节 AES 密钥
   Uint8List? generateAesKey() {
    const chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
    final random = Random.secure(); 
    _aesKeyBytes = Uint8List.fromList(
      List<int>.generate(32, (i) => chars.codeUnitAt(random.nextInt(chars.length)))
    );
    final text = "BwEO2E0JAJnIUs6I4YBimXgQAHBVTk4x";
      _aesKeyBytes = Uint8List.fromList(utf8.encode(text));
    debugPrint('AES Key Generated: ${String.fromCharCodes(_aesKeyBytes!)}');

    debugPrint('AES Key Generated: ${_bytesToHex(_aesKeyBytes!)}');
    return _aesKeyBytes;
  }

  /// 使用 AES 加密文本数据
  /// 返回 base64 编码的加密结果
  String? encryptData(String plaintext) {
    
    if (_aesKeyBytes == null) {
      debugPrint('AES key not initialized');
      return null;
    }

    debugPrint('Encrypting text: $plaintext...');

    try {
      final key = encrypt.Key(_aesKeyBytes!);
      final iv = encrypt.IV.fromLength(16);
      final encrypter = encrypt.Encrypter(
        encrypt.AES(key, mode: encrypt.AESMode.ecb)
      );
      
      final encrypted = encrypter.encrypt(plaintext, iv: iv);
      debugPrint('Data encrypted successfully: encrypted.base64 = ${encrypted.base64}');
      
      return encrypted.base64;
    } catch (e) {
      debugPrint('Encryption failed: $e');
      return null;
    }
  }

  /// 使用 RSA 公钥加密当前的 AES 密钥
  /// 返回 base64 编码的加密结果
  String? encryptAesKeyWithRsa() {
  try {
    // 1. 模拟Swift的输入处理：AES密钥Base64 → UTF-8字节
    final base64Key = base64Encode(_aesKeyBytes!);
    final inputBytes = utf8.encode(base64Key); // 必须与Swift完全一致

    // 2. 严格配置PKCS#1 v1.5填充
    final cipher = PKCS1Encoding(RSAEngine())
      ..init(true, PublicKeyParameter<RSAPublicKey>(
        _parseRsaPublicKey(_rsaPublicKeyPem) as PublicKey, // 确保密钥解析正确
      ));
debugPrint('inputBytes : $inputBytes');
    // 3. 执行加密
    final encrypted = cipher.process(inputBytes);
    final ret = base64Encode(encrypted);
    debugPrint('inputBytes : $ret');
    return ret;

  } catch (e, stack) {
    print('加密失败: $e\n$stack');
    return null;
  }
}


  /// 获取当前 AES 密钥的 Base64 表示（仅用于调试）
  String? get debugAesKeyBase64 => 
      _aesKeyBytes != null ? base64Encode(_aesKeyBytes!) : null;

  // 私有方法 ==============================================
RSAPublicKey? _parseRsaPublicKey(String pemKey) {
  try {
    // 注意：直接传 PEM 字符串，不要解码
    return RSAKeyParser().parse(pemKey) as RSAPublicKey;
  } catch (e) {
    debugPrint('Failed to parse RSA public key: $e');
    return null;
  }
}



  /// 字节数组转十六进制字符串
  String _bytesToHex(Uint8List bytes) {
    return bytes.map((byte) => byte.toRadixString(16).padLeft(2, '0')).join();
  }
}

// provider
final SecureEncryptorProvider = Provider<SecureEncryptor>((ref){
    final envConfig = ref.read(environmentProvider);
    final encryptor = SecureEncryptor(envConfig);
    return encryptor;
});